<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantId"
            placeholder="请输入工厂"
            clearable
            @keyup.enter="search"
            @change="closeDialog(searchParam.plantId)"
          >
            <el-option
              v-for="item in plantList"
              :key="item.id"
              :label="item.organizationCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作中心">
          <el-select
            v-model="searchParam.workCenterId"
            placeholder="请选择工作中心"
            :disabled="searchParam.plantId === ''"
            clearable
            @keyup.enter="search"
          >
            <el-option
              v-for="item in workshopList"
              :key="item.id"
              :label="`${item.workshopCode}-${item.workshopName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班组">
          <el-input
            v-model="searchParam.crewName"
            placeholder="请输入班组"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="班次">
          <el-input
            v-model="searchParam.shiftName"
            placeholder="请输入班次"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker
            v-model="searchParam.startTimeSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getstartTime"
          />
        </el-form-item>
        <el-form-item label="报工状态">
          <el-select
            v-model="searchParam.reportState"
            placeholder="请选择报工状态"
            clearable
          >
            <el-option
              v-for="item in useDictionary('ReportState')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          type="primary"
          plain
          :disabled="ids.length === 0"
          @click="openDialogState()"
          >审批</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="计划外报工单编号"
          prop="unscheduledReportCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="工厂"
          prop="plantCode"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="工作中心"
          prop="workCenterName"
          min-width="160"
          show-overflow-tooltip
        />
        <el-table-column
          label="班组"
          prop="crewName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="班次"
          prop="shiftName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="报工状态"
          prop="reportState"
          min-width="100"
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("ReportState", scope.row.reportState) }}
          </template>
        </el-table-column>
        <el-table-column
          label="报工日期"
          prop="startTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
          :formatter="formatDate"
        />
        <el-table-column
          label="申请时间"
          prop="createTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="申请人"
          prop="memberName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogState(scope.row)"
              v-if="scope.row.reportState == 1 || scope.row.reportState == 3"
              ><i-ep-edit />审批</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mesunscheduledreport-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <mesunscheduledreportapproval-edit
      :visible="stateDialog.visible"
      :title="stateDialog.title"
      :data="stateDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="stateDialog.readvisible"
      @change-visible="changeVisibleState"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "MESMESUNSCHEDULEDREPORT",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mesunscheduledreport/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  unscheduledReportCode: "",
  plantId: "",
  workCenterId: "",
  crewId: "",
  crewName: "",
  shiftName: "",
  startTimeSearch: [],
  startTimeStart: "",
  startTimeEnd: "",
  completeTimeSearch: [],
  completeTimeStart: "",
  completeTimeEnd: "",
  reportState: "",
};

const deleteParam = {
  api: "/mes/mesunscheduledreport/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  getPlantList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
const stateDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mesunscheduledreport/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
// 查询详情
async function getInfoState(id: string) {
  request({
    url: `/mes/mesunscheduledreport/get/${id}`,
    method: "get",
  })
    .then((data) => {
      stateDialog.data = data.data;
      stateDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}
/** 打开计划外报工单表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改计划外报工单";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增计划外报工单";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}
function openDialogState(roleObj?: Object) {
  if (roleObj) {
    //右侧审批
    stateDialog.title = "审批";
    getInfoState(roleObj.id);
    stateDialog.visible = true;
  } else {
    let flag = false;
    tableData.value.forEach((item: any) => {
      ids.value.forEach((items: any) => {
        if (
          item.id == items &&
          (item.reportState == 0 || item.reportState == 2)
        ) {
          flag = true;
        }
      });
    });
    if (flag) {
      ElMessage.error("所选数据存在状态为新建或已同意无法审批！");
      return;
    }
    //选择审批
    stateDialog.title = "审批";
    stateDialog.data = ids.value;
    stateDialog.visible = true;
  }
  stateDialog.readvisible = false;
}
/** 打开计划外报工单表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "计划外报工单详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}
function changeVisibleState(value: boolean) {
  stateDialog.visible = value;
  if (!value) {
    stateDialog.data = {};
  }
}
function getstartTime(data: any) {
  if (data) {
    searchParam.value.createTimeStart = data[0];
    searchParam.value.createTimeEnd = data[1];
  } else {
    searchParam.value.createTimeStart = "";
    searchParam.value.createTimeEnd = "";
  }
}
function getcompleteTime(data: any) {
  if (data) {
    searchParam.value.completeTimeStart = data[0];
    searchParam.value.completeTimeEnd = data[1];
  } else {
    searchParam.value.completeTimeStart = "";
    searchParam.value.completeTimeEnd = "";
  }
}
//工厂列表
const plantList = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
  searchParam.value.plantId = plantList.value[0].id;
  closeDialog(searchParam.plantId);
};
function closeDialog(plantId: String) {
  getWorkshopList(plantId);
  searchParam.value = { ...searchParam.value, workCenterId: "" };
}
//工作中心
const workshopList = ref([]);
const getWorkshopList = async (plantId: String) => {
  const { data } = await request({
    url: "mes/mesworkshop/getList",
    method: "post",
    data: { plantId: plantId },
  });
  workshopList.value = data;
};
/*日期转换*/
function formatDate(row, column) {
  const date = row[column.property];
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}
const confirmList = async (id?: string) => {
  if (id) {
    ids.value = [id];
  }
  ElMessageBox.confirm("确认对已选中的数据项进行关闭吗?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res: any = await request({
      url: "/mes/mesworkorderplan/closePlan",
      method: "post",
      data: { ids: ids.value },
    });
    if (res.code == 200) {
      ElMessage({
        type: "success",
        message: "批量关闭成功",
      });
    }
    getTableList();
  });
};
</script>
<style lang="scss" scoped>
:deep(.el-form .el-form-item__label) {
  width: 63px;
}
</style>
